package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.jxc.dao.GoodsMapper;
import com.atguigu.jxc.dao.ReturnListGoodsMapper;
import com.atguigu.jxc.dao.ReturnListMapper;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.ReturnList;
import com.atguigu.jxc.entity.ReturnListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.ReturnListGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@SuppressWarnings("all")
public class ReturnListGoodsServiceImpl implements ReturnListGoodsService{

    @Autowired
    private ReturnListGoodsMapper returnListGoodsMapper;

    @Autowired
    private ReturnListMapper returnListMapper;

    @Autowired
    private UserDao userDao;

    @Autowired
    private GoodsMapper goodsMapper;


    @Override
    public ServiceVO save(ReturnList returnList, String returnListGoodsStr) {
        // 设置当前操作用户
        User currentUser = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        returnList.setUserId(currentUser.getUserId());

        returnListMapper.insert(returnList);

        List<ReturnListGoods> returnListGoodsList = JSON.parseArray(returnListGoodsStr, ReturnListGoods.class);
        for (ReturnListGoods returnListGoods : returnListGoodsList) {
            returnListGoods.setReturnListId(returnList.getReturnListId());
            returnListGoodsMapper.insert(returnListGoods);

            Goods goods = goodsMapper.findByGoodsId(returnListGoods.getGoodsId());
            goods.setInventoryQuantity(goods.getInventoryQuantity() - returnListGoods.getGoodsNum());
            goods.setState(2);
            goodsMapper.updateGoods(goods);
        }

        return new ServiceVO(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }
}
